import { Space } from 'antd';
import Selector from './lib/Selector';
import { useEffect, useRef, useState } from "react";
import * as echarts from "echarts";
import Line_DATA from "./lib/Line_src";

function Line1Chart(props) {
	const title = props.title;
	const style = props.style;
	const kind = props.kind - 1;
	console.log(props)

	const [Prov1, setProv1] = useState('北京')
	const [Prov2, setProv2] = useState('上海')
	//3个不同的Change对应三次年份选择
	const onChange1 = (value, dateString) => {
		setProv1(value);
		console.log(value)
		console.log("省份1选择为:", dateString)
	}
	const onChange2 = (value, dateString) => {
		setProv2(value);
		console.log("省份2选择为:", dateString)
	}

	const chartRef = useRef(null);

	const chartInit = () => {
		var myChart;
		const renderedInstance = echarts.getInstanceByDom(chartRef.current);
		if (renderedInstance) {
			myChart = renderedInstance;
		} else {
			myChart = echarts.init(chartRef.current);
		}

		var dateList=[];
		for(var i=2010;i<2022;i++)
		{
			dateList.push(i);
		}
		
		var valueList = (Line_DATA[kind].filter(function (item) {
			if (item[0] === Prov1)
				return true;
			else return false;
		})).map(function(item){
			return item[2];
		});
		var valueList2 = (Line_DATA[kind].filter(function (item) {
			// console.log(item)
			if (item[0] === Prov2)
				return true;
			else return false;
		})).map(function(item){
			return item[2];
		});
		//console.log(valueList2)
		myChart.setOption({
			title: [
				{
					left: 'center',
					text: title
				},
			],
			legend: {
				orient: 'vertical',
				left: 'left'
			},
			tooltip: {
				trigger: 'axis',
			},
			toolbox: {
				show: true,
				feature: {
					dataZoom: {
						title: {
							zoom: '区域缩放',
							back: '缩放还原'
						},
						yAxisIndex: 'none'
					},
					dataView: { show: true, readOnly: false, title: "查看数据" },
					restore: { show: true, title: "恢复到初始状态" },
					saveAsImage: { show: true, title: "另存为图片" },
					magicType: {
						title: {
							line: '切换为折线图',
							bar: '切换为柱状图',
						},
						type: ['line', 'bar']
					}
				}
			},
			xAxis: [
				{
					data: dateList
				}
			],
			yAxis: [
				{}
			],
			series: [
				{
					type: 'bar',
					name: Prov1,
					color:'#0F5FA0',
					showSymbol: false,
					data: valueList
				},
				{
					type: 'bar',
					name: Prov2,
					color:'#05E380',
					showSymbol: false,
					data: valueList2,
				}
			]
		})

		window.addEventListener('resize', function () {
			myChart.resize();
		});

	}

	useEffect(() => {
		chartInit();
	}, [Prov1, Prov2, kind]);

	return (
		<div>
			{/*折线图年份选择 */}
			<Space direction="horizontal" size={12} style={{ paddingLeft: 9, paddingTop: 9 }}>
				<Selector onChange={onChange1} DefaultText={"北京"} />
				<Selector onChange={onChange2} DefaultText={"上海"} />
			</Space>
			{/*准备挂载节点*/}
			<div ref={chartRef} style={style}></div>
		</div>

	);
}

export default Line1Chart;